<template>
  <qx-table :option="tableOption" :remoteData="remoteData">
    <template v-slot:top>
      <qx-form v-model="searchForm" :isSearch="true" :option="tableOption" @submit="startSearch"></qx-form>
    </template>
    <template v-slot:packageName="{ row }">
      <q-link @click="handleUpdate(row)">{{ row.packageName }}</q-link>
    </template>
  </qx-table>

  <q-modal v-model="modalVisible" :header="$t('Log4j.LogOutputLevel')" :width="500" btnAlign="center" position="right"
           @beforeClose="beforeClose" @confirm="submitForm">
    <qx-form ref="FormRef" v-model="formInfo" :option="tableOption"></qx-form>
  </q-modal>
</template>

<script setup>
import { i18n } from 'boot/i18n'
import { postAPI } from 'src/api'
import { deepClone } from 'src/utils/utils'
import { computed, onMounted, ref } from 'vue'

const formInfo = ref({})
const FormRef = ref(null)
const searchForm = ref({})
const modalVisible = ref(false)

const options = ['OFF', 'ERROR', 'WARN', 'INFO', 'DEBUG', 'TRACE']
const tableOption = computed(() => {
  return {
    span: 22,
    searchLabelWidth: 90,
    column: [{
      label: i18n.t('Log4j.PackageName'), field: 'packageName', minWidth: 60, slot: true, readonly: true
    }, {
      label: i18n.t('Log4j.LogOutputLevel'), field: 'effectiveLevel', type: 'select', options, display: false
    }, {
      label: i18n.t('Log4j.ValidLogOutputLevels'), field: 'configuredLevel', minWidth: 60,
      search: false, type: 'select', options
    }]
  }
})

const remoteData = ref({ dicUrl: '/rcs/api/logCfg/list' })
onMounted(() => startSearch())

const handleUpdate = row => {
  formInfo.value = deepClone(row)
  modalVisible.value = true
}
const formatSearchForm = () => {
  return { likePackageName: searchForm.value.packageName, equalLevel: searchForm.value.effectiveLevel }
}

const beforeClose = () => {
  if (FormRef.value) FormRef.value.onReset()
  modalVisible.value = false
}

const submitForm = mDone => {
  FormRef.value.validate((form, done) => {
    postAPI('/rcs/api/logCfg/updateLogCfg', form, () => {
      startSearch()
      done()
      if (mDone) mDone()
    }, () => {
      done()
      if (mDone) mDone(false)
    })
  }, () => {
    if (mDone) mDone(false)
  })
}

const startSearch = (_, done) => {
  remoteData.value.params = formatSearchForm()
  if (done) done()
}

</script>